﻿using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Controls;
using AdminApp.Web.Services;
using TheOliver.DigitalSignage.Client.Interfaces;
using TheOliver.DigitalSignage.Client.Logic;

namespace TheOliver.DigitalSignage.Client.Windows
{
    public partial class SelectEventWindow : ChildWindow
    {
        public SelectEventWindow()
        {
            InitializeComponent();
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            Configuration.SelectedEvent = comboBox1.SelectedItem as AdminApp.Web.Event;
            this.DialogResult = true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void eventDomainDataSource_LoadedData(object sender, LoadedDataEventArgs e)
        {
            DigitalSignageDomainContext context =
                     eventDomainDataSource.DomainContext as DigitalSignageDomainContext;

            if (e.HasError)
            {
                if (Configuration.Events != null)
                {

                    // Try to load from cache
                    foreach (var ev in Configuration.Events)
                    {
                        context.Events.Add(ev);
                    }
                    comboBox1.DataContext = context.Events;
                }

                // If everything failes ... show error
                if (context.Events.Count == 0 || context.Events == null)
                {
                    Helper.ShowError(e.Error);
                    e.MarkErrorAsHandled();
                }
            }
            else
            {
                // Save to cache
                Configuration.Events = context.Events;
            }

            if (Configuration.SelectedEvent != null)
            {
                foreach (var ev in context.Events)
                {
                    if (ev.Id == Configuration.SelectedEvent.Id)
                    {
                        comboBox1.SelectedItem = ev;
                        break;
                    }
                }
            }
            OKButton.IsEnabled = true;
            OKButton.Focus();
        }
    }
}

